from django.http import JsonResponse
from django.db import connection
import json
from rest_framework.decorators import api_view
from buildapi.models import BuildingInfo
from zoneapi.models import ZoneInfo
from houseapi.models import HouseInfo
# Create your views here.


@api_view(['POST'])
def dispatcher(request):  

    # try:
    if request.user.is_authenticated:   # 验证Token是否正确
        if request.user.is_active:
            if request.method == 'GET':
                request.params = request.GET

            # POST/PUT/DELETE 请求 参数 从 request 对象的 body 属性中获取
            elif request.method in ['POST','PUT','DELETE']:
                # 根据接口，POST/PUT/DELETE 请求的消息体都是 json格式
                request.params = json.loads(request.body)


            # 根据不同的action分派给不同的函数进行处理
            action = request.params['action']
            if action == 'list':
                return BuildingInfo_list(request)
            elif action == 'add':
                return BuildingInfo_add(request)
            elif action == 're':  
                return BuildingInfo_re(request)
            elif action == 'del':
                return BuildingInfo_del(request)
            elif action == 'like':
                return BuildingInfo_like(request)
            elif action == 'include':
                return BuildingInfo_include(request)
            elif action == 'about':
                return BuildingInfo_about(request)

            else:
                return JsonResponse({'ret': 1, 'msg': '不支持该类型http请求'})
    else:
        return JsonResponse({'ret': 2, "msg": "token验证失败"})


def BuildingInfo_list(request):
    data = json.loads(request.body)  
    openid = data['openid']
    page_max = int(data['page_max'])
    page = int(data['page'])
    try:
        index = BuildingInfo.objects.filter(building_openid=openid).values().order_by('building_id')[page_max*page-page_max:page_max*page]
        count = BuildingInfo.objects.filter(building_openid=openid).count()

        return JsonResponse({'ret':0,'data':list(index),'count':count})
    except Exception as e:
        return JsonResponse({
                'ret': 1,
                'msg': "列表获取失败，发生异常:{}".format(e)
            })


def BuildingInfo_add(request):
    data = json.loads(request.body)  
    try:
        building_nbr = data['building_nbr']
        building_about_id = data['building_about_id']
        building_electric_price = data['building_electric_price']
        building_water_price = data['building_water_price']
        building_about_ikuai = data['building_about_ikuai']
        building_openid = data['building_openid']
        building_network_tariff = data['building_network_tariff']

        if BuildingInfo.objects.filter(building_nbr=building_nbr,building_openid=building_openid).exists():
            return JsonResponse({'ret':2 , 'msg':"该楼栋编号：{} 已经存在".format(building_nbr)})
        if ZoneInfo.objects.filter(zone_id=building_about_id).exists() is False:
            return JsonResponse({'ret':2 , 'msg':"该小区编号：{} 不存在".format(building_about_id)})
        if BuildingInfo.objects.filter(building_about_ikuai=building_about_ikuai).exists():
            return JsonResponse({'ret':3,'msg':'该设备id已被绑定'})
        else:
            index = ZoneInfo.objects.filter(zone_id=building_about_id).values()
            zone_name = list(index)[0]['zone_name']

            BuildingInfo.objects.create(
            building_openid = building_openid,
            building_nbr = building_nbr,
            building_about_name = zone_name,
            building_electric_price = building_electric_price,
            building_water_price = building_water_price,
            building_price = 0,
            building_count = 0,
            building_network_tariff = building_network_tariff,
            building_electric = 0,
            building_water = 0,
            building_idle_count = 0,
            building_about_ikuai = building_about_ikuai,
            building_about_id = building_about_id)
            return JsonResponse({'ret':0})

    except Exception as e:
        return JsonResponse({
                'ret': 1,
                'msg': "信息添加失败，发生异常:{}".format(e)
            })


def BuildingInfo_re(request):
    data = json.loads(request.body)  
    cursor = connection.cursor()
    try:
        key = list(data['key'])
        value = list(data['value'])
        building_id = data['building_id']

        if len(key) > 0 :
            for i in range(len(key)):
                if key[i] == 'building_about_ikuai':
                    if BuildingInfo.objects.filter(building_id=building_id,building_about_ikuai=value[i]).exists():
                        cursor.execute(" UPDATE building_info SET {} = '{}' WHERE building_id = '{}' ".format(key[i],value[i],building_id))
                    elif value[i] == 'null':
                        Building = BuildingInfo.objects.get(building_id=building_id)
                        Building.building_about_ikuai = None
                        Building.save()
                    elif BuildingInfo.objects.filter(building_about_ikuai=value[i]).exists():
                        return JsonResponse({'ret':2,'msg':'该设备已被其他楼栋绑定，请解绑后再试'})
                    else:
                        cursor.execute(" UPDATE building_info SET {} = '{}' WHERE building_id = '{}' ".format(key[i],value[i],building_id))
                else:
                    cursor.execute(" UPDATE building_info SET {} = '{}' WHERE building_id = '{}' ".format(key[i],value[i],building_id))
                    
            return JsonResponse({'ret':0})
    except BuildingInfo.DoesNotExist as e:
        return JsonResponse({
                'ret': 1,
                'msg': "修改失败，发生异常:{}".format(e)
            })

def BuildingInfo_del(request):
    data = json.loads(request.body)
    try:
        building_id = list(data['building_id'])

        if len(building_id) > 0 :
            for i in range(len(building_id)):
                if HouseInfo.objects.filter(house_about_id=building_id[i]).exists():
                    return JsonResponse({
                    'ret': 2,
                    'msg': "请先删除或更改：{} 已关联的房间".format(building_id[i])
                    })
                index = BuildingInfo.objects.get(building_id=building_id[i])
                index.delete()
    except BuildingInfo.DoesNotExist as e:
        return JsonResponse({
            'ret': 1,
            'msg': "信息删除失败，发生异常：{}".format(e)
        })
    return JsonResponse({'ret':0})

def BuildingInfo_like(request):
    data = json.loads(request.body)
    try:
        control = data['control']
        openid = data['openid']
        building_nbr = data['building_nbr']
        if control == 'pc':
            index = BuildingInfo.objects.filter(building_nbr__icontains=building_nbr,building_openid=openid).values()
        elif control == 'wx':
            building_about_id = data['building_about_id']
            index = BuildingInfo.objects.filter(building_nbr__icontains=building_nbr,building_openid=openid,building_about_id=building_about_id).values()
    except BuildingInfo.DoesNotExist as e:
        return JsonResponse({
            'ret': 1,
            'msg': "模糊查询失败，发生异常：{}".format(e)
        })
    return JsonResponse({'ret':0,'data':list(index)})


def BuildingInfo_include(request):
    data = json.loads(request.body)
    try:
        building_id = data['building_id']
        build = BuildingInfo.objects.filter(building_id=building_id).values()
        index = list(build)[0]
        zone = ZoneInfo.objects.filter(zone_id=index['building_about_id']).values()
    except BuildingInfo.DoesNotExist as e:
        return JsonResponse({
            'ret': 1,
            'msg': "查询失败，发生异常：{}".format(e)
        })
    return JsonResponse({'ret':0,'build':list(build),'zone':list(zone)})


def BuildingInfo_about(request):
    data = json.loads(request.body)
    try:
        building_about_id = data['building_about_id']
        build = BuildingInfo.objects.filter(building_about_id=building_about_id).values()
        index = list(build)
    except BuildingInfo.DoesNotExist as e:
        return JsonResponse({
            'ret': 1,
            'msg': "查询失败，发生异常：{}".format(e)
        })
    return JsonResponse({'ret':0,'data':index})